package com.sherlockHolmes.init.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sherlockHolmes.init.base.utils.IPUtils;
import com.sherlockHolmes.init.base.utils.JWTUtil;
import com.sherlockHolmes.init.base.utils.Uid;
import com.sherlockHolmes.init.entity.dao.UserInfo;
import com.sherlockHolmes.init.entity.dto.AssetDTO;
import com.sherlockHolmes.init.entity.dto.UserInfoDTO;
import com.sherlockHolmes.init.mapper.UserInfoMapper;
import com.sherlockHolmes.init.recommend.PeopleNearby;
import com.sherlockHolmes.init.service.SearchService;
import com.sherlockHolmes.init.service.UserInfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.Date;

/**
* @author 四月一日 君寻
* &#064;description  针对表【user_info(用户表)】的数据库操作Service实现
* &#064;createDate  2024-03-25 15:53:44
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo>
    implements UserInfoService, SearchService {
    @Resource
    private UserInfoMapper userMapper;
    @Resource
    private PeopleNearby peopleNearby;

    /**
     * 根据账号查询用户
     */
    @Override
    public UserInfo getUserByName(String username) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name", username);
        return userMapper.selectOne(queryWrapper);
    }

    @Override
    public String login(UserInfo user, HttpServletRequest request) throws Exception {
        UserInfo userInfo = getUserByName(user.getUserName());//根据用户名获取用户对象
        //检查账号是否存在,不存在抛异常
        if(userInfo==null){
            throw new RuntimeException("账号错误");
        }//密码是否正确，密码错误抛异常
        if(!user.getPassword().equals(userInfo.getPassword())){
            throw new RuntimeException("密码错误");
        }//检查通过生成token令牌
        String sign = JWTUtil.sign(user.getUserName(), user.getPassword());//生成token令牌
     //   ValueOperations<Object, Object> token = redisTemplate.opsForValue();
        HttpSession session = request.getSession();
        session.setAttribute("username", user.getUserName());
       // token.set("id",user.getId());//将用户id存入redis
        String ipAddress = IPUtils.getIpAddress(request);
        //记录登录人的经纬度到redis
        peopleNearby.online(user.getUserName(),ipAddress);
        return sign;
    }

    @Override
    public Object register(UserInfo user) {
        UserInfo one = new LambdaQueryChainWrapper<>(userMapper)
                .eq(UserInfo::getEmail, user.getEmail())
                .or()
                .eq(UserInfo::getNickName, user.getNickName())
                .one();
        if(ObjectUtil.isNotEmpty(one)){
            if(one.getNickName().equals(user.getNickName())){
                return "用户名已存在";
            } else if (one.getEmail().equals(user.getEmail())){
                return "邮箱已注册";
            }
        }
        user.setUserName(Uid.getAccount());
        return userMapper.insert(user);
    }

    /**
     * 更新用户信息
     */
    @Override
    public int updateUserInfo(UserInfoDTO userInfo) {
        UserInfo user = new UserInfo();
        BeanUtils.copyProperties(userInfo,user);
        user.setUpdateTime(new Date());
        if(ObjectUtil.isNotEmpty(userInfo.getHobby())){
            String s = JSONUtil.toJsonStr(userInfo.getHobby());
            user.setHobby(s);
        }
        if(ObjectUtil.isNotEmpty(userInfo.getLabel())){
            String s = JSONUtil.toJsonStr(userInfo.getLabel());
            user.setLabel(s);
        }
        return userMapper.updateById(user);
    }

    @Override
    public int addAsset(AssetDTO asset) {
        UserInfo userInfo = userMapper.selectById(asset.getId());
        if("1".equals(asset.getType())){//金币增加
            BigDecimal gold = userInfo.getGold();
            gold = gold.add(BigDecimal.valueOf(asset.getNum()));
            userInfo.setGold(gold);
            updateById(userInfo);
        }else if("2".equals(asset.getType())){//硬币增加
            BigDecimal coin = userInfo.getCoin();
            coin = coin.add(BigDecimal.valueOf(asset.getNum()));
            userInfo.setGold(coin);
           updateById(userInfo);
        }else {
           throw new RuntimeException("不合法的参数");
        }
        return 1;
    }

    @Override
    public int reduceAsset(AssetDTO asset) {
        UserInfo userInfo = userMapper.selectById(asset.getId());
        if("1".equals(asset.getType())){//金币减少
            BigDecimal gold = userInfo.getGold();
            gold = gold.subtract(BigDecimal.valueOf(asset.getNum()));
            userInfo.setGold(gold);
            updateById(userInfo);
        }else if("2".equals(asset.getType())){//硬币减少
            BigDecimal coin = userInfo.getCoin();
            coin = coin.subtract(BigDecimal.valueOf(asset.getNum()));
            userInfo.setGold(coin);
            updateById(userInfo);
        }else {
            throw new RuntimeException("不合法的参数");
        }
        return 1;
    }
    /**
     * 获取当前用户信息
     */
    public UserInfo getUserInfo(HttpServletRequest request){
        HttpSession session = request.getSession();
        String username = (String) session.getAttribute("username");
        UserInfo userInfo = getUserByName(username);
        return userInfo;
    }
}




